package lock;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * wait / notifyAll
 * @author jiangwz
 * @create 2019/7/9.
 */
public class Container01 {

    // 仓库容量
    private final int MAX_SIZE = 10;
    // 仓库存储的载体
    private LinkedList<Object> list = new LinkedList<>();


    public synchronized void put(Object o){
        while (list.size() >= MAX_SIZE) {
            synchronized (this) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                }
            }
        }
        list.push(o);
        System.out.println(Thread.currentThread().getName() + " put当前容器里有"+ list.size() + "个对象");
        this.notifyAll();
    }

    public synchronized Object get(){
        while (list.size() == 0){
            synchronized (this){
                try {
                    this.wait();

                } catch (InterruptedException e) {
                }
            }
        }
        Object o = list.removeFirst();
        System.out.println(Thread.currentThread().getName() + " get当前容器里有"+ list.size() + "个对象");
        this.notifyAll();
        return o;
    }

    public static void main(String[] args){
        Container01 c = new Container01();
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.submit(() -> {
                while (true) {
                    Object o = c.get();
//                    System.out.println(o);
                }
            });
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 2; i++) {
            executorService.submit(() -> {
                for (int j = 0; j < 25; j++) {
                    c.put(j);
                }
            });
        }


    }

}
